#include "mwfilter.h"
#include <cstring> // for memset

MovingAverageFilter::MovingAverageFilter(int windowSize)
    : windowSize(windowSize), index(0), count(0), sum(0.0f)
{
    buffer = new float[windowSize];
    std::memset(buffer, 0, sizeof(float) * windowSize);
}

MovingAverageFilter::~MovingAverageFilter()
{
    delete[] buffer;
}

float MovingAverageFilter::update(float newValue)
{
    // 从总和中减去被替换的旧值
    sum -= buffer[index];

    // 替换旧值并加入新值
    buffer[index] = newValue;
    sum += newValue;

    // 更新索引和计数器
    index = (index + 1) % windowSize;
    if (count < windowSize)
        count++;

    return sum / count;
}

void MovingAverageFilter::reset()
{
    std::memset(buffer, 0, sizeof(float) * windowSize);
    index = 0;
    count = 0;
    sum = 0.0f;
}
